/*
杨辉三角和二项式

输入格式：一个正整数n
输出格式：n层的杨辉三角和(a+b)^n的展开式

示例输入：
13
示例输出：
                        1
                      1   1
                    1   2   1
                  1   3   3   1
                1   4   6   4   1
              1   5   10  10  5   1
            1   6   15  20  15  6   1
          1   7   21  35  35  21  7   1
        1   8   28  56  70  56  28  8   1
      1   9   36  84  126 126 84  36  9   1
    1   10  45  120 210 252 210 120 45  10  1
  1   11  55  165 330 462 462 330 165 55  11  1
1   12  66  220 495 792 924 792 495 220 66  12  1

a^13 + 13a^12b + 78a^11b^2 + 286a^10b^3 + 715a^9b^4 + 1287a^8b^5 + 1716a^7b^6 + 1716a^6b^7 + 1287a^5b^8 + 715a^4b^9 + 286a^3b^10 + 78a^2b^11 + 13ab^12 + b^13
*/

#include <iostream>
#include <iomanip>
#include <vector>
#include <string>
#include <cmath>

using std::cout;
using std::cin;
using std::vector;
using std::string;
using std::ostream;
using std::left;

ostream& operator<<(ostream& out, const vector<vector<int>>& triangle);        // 定义<<运算符，用于输出杨辉三角
vector<vector<int>> yh_triangle(int layer);        // 生成layer层的杨辉三角。layer必须为正整数
void bin_exp(int power);             // 输出(a+b)^power的展开式。power必须为正整数
string not1num(int num, const string& prefix ="") { return ((num==1) ? "" : prefix+std::to_string(num)); }

int main()
{
    cout.sync_with_stdio(false);
    cout << "请输入层数：";
    int layer;
    cin >> layer;
    cout << yh_triangle(layer) << '\n';
    bin_exp(layer);
    return 0;
}

vector<vector<int>> yh_triangle(int layer)
{
    vector<vector<int>> triangle;
    triangle.push_back(vector<int>{1});
    for (int i{1}; i!=layer; ++i) {
        vector<int> row {1};
        vector<int>& prev_row {triangle.back()};
        for (auto i=prev_row.begin()+1; i!=prev_row.end(); ++i)
            row.push_back(*i+*(i-1));
        row.push_back(1);
        triangle.push_back(std::move(row));
    }
    return triangle;
}

ostream& operator<<(ostream& out, const vector<vector<int>>& triangle)
{
    int max_num {triangle.back()[triangle.size()/2]};
    int width {static_cast<int>(log10(max_num))+2};
    out << left;
    for (unsigned row{}; row!=triangle.size(); ++row) {
        auto whitespace = width*(triangle.size()-row-1)/2;
        out << string(whitespace, ' ');
        for (auto i : triangle[row])
            out << std::setw(width) << i;
        out << '\n';
    }
    return out;
}

void bin_exp(int power)
{
    vector<int> coe {yh_triangle(power+1).back()};
    for (int i{}; i<=power; ++i) {
        cout << not1num(coe[i]);
        if (i != power)
            cout << 'a' << not1num(power-i, "^");
        if (i != 0)
            cout << 'b' << not1num(i, "^");
        if (i != power)
            cout << " + ";
    }
}

